import React, { useState } from 'react';
import { Image, View, Input } from '@tarojs/components';
import pSearch from '@/images/common/searchIcon.png';
import pClear from '@/images/common/searchClose.png';
import './index.scss';

const Search = ({
  button = false,
  defaultValue = '',
  className = '',
  onlyRedirect = false,
  handleSearch = null,
  placeholder = '搜索商品',
  onClear = () => {},
}) => {
  const [searchValue, setSearchValue] = useState(defaultValue);

  const inputHandler = (e) => {
    setSearchValue(e.detail.value);
  };

  const inputClear = () => {
    setSearchValue('');

    onClear();
  };

  return (
    <View
      className={['search-wrap', className].join(' ')}
      onClick={() => onlyRedirect && handleSearch()}
    >
      <View className="left">
        <Image className="searchIcon" src={pSearch} />
        <Input
          className="searchInput"
          type="text"
          confirmType="search"
          disabled={onlyRedirect}
          placeholder={placeholder}
          placeholderClass="inputPlaceholder"
          maxLength={16}
          value={searchValue}
          onConfirm={() => {
            handleSearch(searchValue);
          }}
          onInput={(e) => {
            inputHandler(e);
          }}
        />
        {searchValue.length > 0 && !onlyRedirect && (
          <View className="searchClear" onClick={inputClear}>
            <Image className="icon" src={pClear} />
          </View>
        )}
      </View>
      {button?<View className="right" onClick={() => !onlyRedirect && handleSearch(searchValue)}>
        搜索
      </View>:null}
    </View>
  );
};

export default Search;
